import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Radio, Card, Table, Select, message, Pagination, Tooltip } from 'antd';
import FilterTool from '../../../components/FilterTool';
import services from '../../../services/api';
import LineStackChart from '../../../components/Chart/LineStackChart';
// import PieChart from '../../../components/Chart/PieChart';
import CodeLabel from '../../../components/CodeLabel';
import moment from 'moment';

const Option = Select.Option;

export default function Stasistics(props) {
  const queryParamsRef = useRef({});
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [type, setType] = useState(1);
  const [strategyId, setStrategyId] = useState('');
  // const [requestTotal, setRequestTotal] = useState([]); //请求总量
  // const [strategyHitTotal, setStrategyHitTotal] = useState([]); //策略命中次数
  const [hitData, setHitData] = useState([]); // 命中展示数据
  // const [strategyHitCategory, setStrategyHitCategory] = useState([]); //策略命中分类
  const [policyList, setPolicyList] = useState([]);
  const [versionList, setVersionList] = useState([]);
  const [version, setVersion] = useState([]);
  const [pageParamOther, setPageParamOther] = useState({});
  const api = props.api || 'produce' // 不同模块下存在相同的接口

  useEffect(() => {
    queryParamsRef.current.pageParam = { current_page: currentPage, page_size: pageSize };
    refreshRequestTime();
    getPolicyList();
  }, []);

  function refreshRequestTime() {
    queryParamsRef.current.request_time = moment().format('YYYY-MM-DD HH:mm:ss');
  }
  function freshQueryList(params) {}

  function refreshFilter(params) {
    if (Object.keys(params).length > 0) {
      setType('');
      queryParamsRef.current.type = '';
      queryParamsRef.current.queryParam = params;
    } else {
      queryParamsRef.current.type = type;
    }
    refreshRequestTime();
    refreshInitPagination();
    query();
    trendHitDetail();
  }

  function query() {
    if (!queryParamsRef.current.version) return
    const params = {
      ...queryParamsRef.current.queryParam,
      strategy_id: queryParamsRef.current.strategyId,
      strategy_version: queryParamsRef.current.version,
      request_time: queryParamsRef.current.request_time,
    };
    if (queryParamsRef.current.type !== '') {
      params.type = queryParamsRef.current.type;
    }
    services[api].trend(params).then((res) => {
      if (res.code === 0) {
        setHitData(res.data)
      }
    });
  }

  function trendHitDetail() {
    if (!queryParamsRef.current.version) return
    const params = {
      ...queryParamsRef.current.queryParam,
      ...queryParamsRef.current.pageParam,
      strategy_id: queryParamsRef.current.strategyId,
      strategy_version: queryParamsRef.current.version,
      request_time: queryParamsRef.current.request_time,
    };
    if (queryParamsRef.current.type !== '') {
      params.type = queryParamsRef.current.type;
    }
    services[api].trendHitDetail(params).then((res) => {
      if (res.code === 0) {
        setData(res.data.list);
        setCurrentPage(res.data.currentPage);
        setPageSize(res.data.pageSize);
        setTotalCount(res.data.totalCount);
        const { currentPage, pageSize, list, ...other } = res.data;
        setPageParamOther(other);
      }
    });
  }

  function getPolicyList() {
    services.policy.strategyReleaseAll({ event_id: props.event_id }).then((res) => {
      if (res.code === 0) {
        setPolicyList(res.data);
        setStrategyId(res.data[0].strategy_id)
        queryParamsRef.current.strategyId = res.data[0].strategy_id;
      } else {
        message.error(res.msg);
      }
    });
  }

  function getVersion(strategy_id) {
    services.produce.allVersions({ strategy_id, event_id: props.event_id, is_publish: 2 }).then(res => {
      if (res.code === 0) {
        setVersionList(res.data)
        setVersion(res.data[0] ? res.data[0].version : undefined)
        queryParamsRef.current.version = res.data[0] ? res.data[0].version : undefined
        // refreshRequestTime();
        // refreshInitPagination();
        // query();
        // trendHitDetail();
      } else {
        message.error(res.msg);
      }
    });
  }

  function changePolicy(value) {
    setStrategyId(value);
    setVersion(undefined)
    queryParamsRef.current.strategyId = value;
    queryParamsRef.current.version = undefined
  }

  function changeVersion(value) {
    setVersion(value)
    queryParamsRef.current.version = value
    // refreshRequestTime();
    // refreshInitPagination();
    // query();
    // trendHitDetail();
  }

  useEffect(() => {
    if (strategyId) {
      getVersion(strategyId)
    }
  }, [strategyId])

  useEffect(() => {
    if (version) {
      refreshRequestTime();
      refreshInitPagination();
      query();
      trendHitDetail();
    }
  }, [version])

  function handleChange(e) {
    setType(e.target.value);
    queryParamsRef.current.type = e.target.value;
    queryParamsRef.current.queryParam = {};
    refreshRequestTime();
    refreshInitPagination();
    query();
    trendHitDetail();
  }

  function onChangePagination(page) {
    if (
      pageParamOther.previousId &&
      pageParamOther.nextId &&
      pageParamOther.previousPage &&
      pageParamOther.totalCount
    ) {
      queryParamsRef.current.pageParam = {
        current_page: page,
        previous_id: pageParamOther.previousId,
        next_id: pageParamOther.nextId,
        previous_page: pageParamOther.previousPage,
        total_count: pageParamOther.totalCount,
        page_size: pageSize,
      };
    } else {
      queryParamsRef.current.pageParam = { current_page: page, page_size: pageSize };
    }

    trendHitDetail();
  }

  function refreshInitPagination() {
    queryParamsRef.current.pageParam = { current_page: 1, page_size: pageSize };
  }

  function getColumns() {
    return [
      {
        title: '发生时间',
        dataIndex: 'req_time',
        key: 'req_time',
        ellipsis: true,
        width: 120,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '请求策略',
        dataIndex: 'strategy_name',
        key: 'strategy_name',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '评估结果',
        dataIndex: 'risk_level',
        key: 'risk_level',
        render: (text, record) => {
          return (
            <Tooltip title={<CodeLabel value={text} code={'risk_level'} />}>
              <div>
                <CodeLabel value={text} code={'risk_level'} />
              </div>
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '用户ID',
        dataIndex: 'user_id',
        key: 'user_id',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: 'IP',
        dataIndex: 'ip',
        key: 'ip',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '地区',
        dataIndex: 'ip_loc',
        key: 'ip_loc',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '设备指纹',
        dataIndex: 'dev_id',
        key: 'dev_id',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '设备类型',
        dataIndex: 'dev_type',
        key: 'dev_type',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
    ];
  }

  const filter = [
    {
      type: 'rangepicker',
      key: 'start',
      name: ['start', 'end'],
      placeholder: ['开始时间', '结束时间'],
      showTime: false,
      changeSubmit: true,
      format: 'YYYY-MM-DD',
    },
  ];
  // const featureTrend = [
  //   {
  //     name: '请求总量',
  //     value: requestTotal,
  //   },
  //   {
  //     name: '命中次数',
  //     value: strategyHitTotal,
  //   },
  // ];
  return (
    <div className='tantuer'>
      <Row type='flex' justify='space-between'>
        <Col span={12}>
          <Radio.Group value={type} buttonStyle='solid' onChange={handleChange}>
            <Radio.Button value={1}>每分钟</Radio.Button>
            <Radio.Button value={2}>每5分钟</Radio.Button>
            <Radio.Button value={3}>每15分钟</Radio.Button>
            <Radio.Button value={4}>每小时</Radio.Button>
          </Radio.Group>
        </Col>
        <Col span={8}>
          <FilterTool
            justify='end'
            data={filter}
            colNum={1}
            query={freshQueryList}
            refreshFilter={refreshFilter}
            isOnChange={true}
            reload={type !== ''}
            isSearchNotSpaceBetween={true}
          />
        </Col>
      </Row>
      <Row type='flex' gutter={20} justify='space-between' style={{ marginTop: '10px' }}>
        <Col span={24}>
          <Card
            title='命中展示'
            headStyle={{ height: '62px' }}
            extra={
              <div>
                <span>策略</span>
                <Select
                  placeholder='请选择'
                  onChange={changePolicy}
                  style={{ width: '150px', marginLeft: 5 }}
                  dropdownMatchSelectWidth={false}
                  value={strategyId}
                >
                  {policyList.map((item) => {
                    return (
                      <Option value={item.strategy_id} key={item.strategy_id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
                <span style={{ marginLeft: 10 }}>版本</span>
                <Select
                  placeholder='请选择'
                  onChange={changeVersion}
                  style={{ width: '80px', marginLeft: 5 }}
                  dropdownMatchSelectWidth={false}
                  value={version}
                >
                  {versionList.map((item) => {
                    return (
                      <Option value={item.version} key={item.version}>
                        {item.version}
                      </Option>
                    );
                  })}
                </Select>
              </div>
            }
          >
            <LineStackChart
              width='100%'
              height='350px'
              dataSource={hitData}
              legend={hitData.map((item) => item.name)}
              xAxisKey={'index'}
              dataKey={'requests'}
            />
          </Card>
        </Col>
        {/* <Col span={12}>
          <Card title='命中分类' headStyle={{ height: '62px' }}>
            <PieChart width='100%' height='350px' id='pi' dataSource={strategyHitCategory} />
          </Card>
        </Col> */}
      </Row>
      <Card title='命中详情' style={{ margin: '20px 0 0 0', paddingBottom: '10px' }}>
        <Table columns={getColumns()} dataSource={data} rowKey='req_id' pagination={false} className='fixed' />
        {currentPage && totalCount > 0 && (
          <Row type='flex' justify={'end'} align='middle' style={{ margin: '20px 0' }}>
            <Col>
              <Pagination
                showQuickJumper={!pageParamOther}
                current={currentPage}
                pageSize={pageSize}
                total={totalCount}
                showTotal={(total) => {
                  return pageParamOther.exceededNum === 1 ? `总共 ${total}+ 条` : `总共 ${total} 条`;
                }}
                onChange={(page) => onChangePagination(page)}
                style={{ textAlign: 'right' }}
              />
            </Col>
          </Row>
        )}
      </Card>
    </div>
  );
}
